package net.jgrm.order.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: houyong
 * @date: 2025年08月20日 17:51
 */
public class MigratableTask implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(MigratableTask.class);

    private final long taskId;
    private final Runnable originalTask;
    private final long createTime;
    private final AtomicInteger executionAttempts;

    public MigratableTask(long taskId, Runnable originalTask) {
        this.taskId = taskId;
        this.originalTask = originalTask;
        this.createTime = System.currentTimeMillis();
        this.executionAttempts = new AtomicInteger(0);
    }

    @Override
    public void run() {
        try {
            executionAttempts.incrementAndGet();
            logger.debug("执行任务 {}: 第 {} 次尝试", taskId, executionAttempts.get());
            originalTask.run();
            logger.debug("任务 {} 执行完成", taskId);
        } catch (Exception e) {
            logger.error("任务 {} 执行失败: 第 {} 次尝试", taskId, executionAttempts.get(), e);
            throw e; // 重新抛出异常，让上层处理
        }
    }

    public long getTaskId() {
        return taskId;
    }

    public int getExecutionAttempts() {
        return executionAttempts.get();
    }

    public long getCreateTime() {
        return createTime;
    }
}
